import string
import random

from baykeadmin.config import default

def random_string(length=default.FONT_CAPTCHA_LENGTH):
    """
    生成随机字符串
    :param length: 字符串长度
    :return: 随机字符串
    """
    if not isinstance(length, int):
        raise TypeError('length must be int')

    chars = string.ascii_letters + string.digits
    return ''.join(random.sample(chars, length))

def generate_catcha_image(width=80, height=30, font_size=27, font_path='', length=default.FONT_CAPTCHA_LENGTH):
    """
    生成验证码图片
    :param width: 图片宽度
    :param height: 图片高度
    :param font_size: 字体大小
    :param font_path: 字体路径
    :param length: 字符长度
    :return: 图片及验证码字符串
    """
    # pillow
    from PIL import Image, ImageDraw, ImageFont
    # 创建一个画布
    image = Image.new('RGBA', (width, height), color=(255, 255, 255, 0))
    draw = ImageDraw.Draw(image)
    # 加载字体
    from baykeadmin.config import default
    if not font_path:  # 默认字体
        font_path = default.FONT_CAPTCHA_PATH

    font = ImageFont.truetype(font_path, font_size)
    # 生成随机验证码
    random_str = random_string(length)
    # 绘制一个彩色验证码
    x, y = 1, 0
    for i in range(length):
        # rgb = (0, 0, 0)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.text((x, y), random_str[i], font=font, fill=color)
        x += font_size * 0.7 # 让每一个字符之间有一个间隔

    # 绘制随机的干扰点和干扰线
    for _ in range(random.randint(0, 15)):
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.point((random.randint(0, width), random.randint(0, height)), fill=color)
    # 绘制干扰线
    for _ in range(random.randint(0, 10)):
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.line(
            (random.randint(0, width), random.randint(0, height), 
            random.randint(0, width), random.randint(0, height)), 
            fill=color
        )
    return image, random_str


if __name__ == '__main__':
    generate_catcha_image()